/*
 * @Author: 鸿羽飞舟 2653235481@qq.com
 * @Date: 2022-08-19 09:14:49
 * @LastEditors: 鸿羽飞舟 2653235481@qq.com
 * @LastEditTime: 2022-08-19 09:22:28
 * @FilePath: \学习笔记-1c:\Users\zhongyuhong\Documents\Tencent Files\2653235481\FileRecv\实训三\js刷题\08.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// *编写一个函数来查找字符串数组中的最长公共前缀。
function longestCommonPrefix(strs) {
    if(strs.length>1){
        // 重新排序，获取数组中最短那个，strs[0]
        strs.sort(function(a,b){return a.length-b.length});
        // console.log(strs);          //[ 'flow', 'flower', 'flight' ]
        var s0=strs[0],a,b='';
        for(var j=1;j<strs.length;j++){
            for(var i=1;i<=s0.length;i++){
                // s0的拼凑，从第一位到后面i位,判断最长公共前缀a
                a=s0.slice(0,i)
                // 判断相同长度的前缀是否相等，相等返回a,不等返回最长a
                if(a==strs[j].slice(0,i)){
                    b=a;
                    c=i;
                }else{
                    if(i==1){
                        return '';
                    }
                }
            }
            s0=b;
        }
        return b;
    }else{
        return strs.join('');
    }
};
console.log(longestCommonPrefix(["flower","flow","flight"]));       //'fl'
console.log(longestCommonPrefix(["dog","racecar","car"]));          //''
console.log(longestCommonPrefix(["car","cir","card"]));             //'c'